import { Table, Space, Button, message, Input } from 'antd'
import React, { useRef, useState, useEffect, useImperativeHandle } from 'react'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import {
  templatePageList,
  deleteTemplate,
} from '@/api/base-config.js'
import ConfigAdd from './config-add/index.jsx'
import FlowStepTable from '@/components/flow-step-table/index.jsx'
import ConfigFormContext from './configFormContext.js'

const { Search } = Input
export const FlowStepList = React.forwardRef((props, ref) => {
  const { type, config } = props

  const configAddRef = useRef()

  const containerRef = useRef()

  const onAdd = () => {
    configAddRef.current.open()
  }

  const onEdit = (record) => {
    configAddRef.current.open(record)
  }

  const onDelete = (record) => {
    deleteTemplate({id: record.id, isConfirm: true}).then(() => {
      message.success('删除成功')
      onRefresh()
    })
  }

  const columns = [
    {
      title: '流程步名称',
      dataIndex: 'templateName',
    },
    {
      title: '流程步编码',
      dataIndex: 'templateCode',
    },
    {
      title: '操作',
      dataIndex: 'key',
      width: '100px',
      render: (key, record, index) => {
        return (
          <Space>
            <Button
              className='icon-btn'
              type='text'
              icon={<EditOutlined />}
              size="small"
              onClick={() => onEdit(record)}
            />
            <Button
              className='icon-btn'
              type='text'
              icon={<DeleteOutlined />}
              size="small"
              onClick={() => onDelete(record)}
            />
          </Space>
        )
      },
    },
  ]

  const [data, setData] = useState([])

  const [query, setQuery] = useState({
    templateName: '',
    pageNum: 1,
    pageSize: 15
  })
  const [total, setTotal] = useState(0)

  const requestData = () => {
    if (!type || !type.id) {
      setData([])
      setTotal(0)
      return
    }

    templatePageList({
      typeId: type.id,
      templateType: config.value,
      ...query
    }).then((res) => {
      const { data } = res
      let list = data.pageInfo.list
      setTotal(data.pageInfo.total)
      setData(list)
    })
  }

  const onRefresh = () => {
    requestData()
  }

  useEffect(() => {
    requestData()
  }, [type, query, config])

  useImperativeHandle(
    ref,
    () => ({
      addFlowStep() {
        onAdd()
      },
    }),
    [type, query, config]
  )
  

  const [scroll, setScroll] = useState()
  useEffect(() => {
    if (containerRef.current) {
      let y = containerRef.current.clientHeight - 90
      y = data.length * 48 < y ? false : y
      setScroll(y ? { y } : null)
    }
  }, [containerRef])


  const configFormContextValue = {
    treeTypeCode: 2,
    showIcon: true
  }

  const timer = useRef(null)

  const onSearchChange = (e) => {
    clearTimeout(timer.current)
    
    timer.current = setTimeout(() => {
      setQuery({
        ...query,
        templateName: e.target.value
      })
    }, 500)
  }

  const onSearch = (value) => {
    requestData({
     ...query,
      templateName: value
    })
  }

  const pagination = {
    showTotal() {
      return `共 ${total} 条`
    },
    current: query.pageNum,
    total: total,
    showSizeChanger: true,
    pageSize: query.pageSize,
    onChange(current, pageSize){
      setQuery({
        ...query,
        pageNum: current,
        pageSize: pageSize
      })
    }
  }

  return (
    <ConfigFormContext.Provider value={configFormContextValue}>
      <div className='top-bottom-layout'>
      <Search
        placeholder="请输入关键字查询"
        style={{ width: '20%', marginBottom: 10 }}
        onChange={onSearchChange}
        onSearch={onSearch}
      />  
        <div ref={containerRef} className='flex-1'>
          <Table rowKey="id" columns={columns} dataSource={data} scroll={scroll} pagination={pagination}></Table>
        </div>
      </div>
      <ConfigAdd
        ref={configAddRef}
        type={type}
        config={config}
        show-add={false}
        onRefresh={onRefresh}
        tableCom={FlowStepTable}
        hideList={true}
      />
    </ConfigFormContext.Provider>
  )
})

FlowStepList.displayName = 'FlowStepList'

export default FlowStepList
